package com.zjt.takeoutproject.controller;

import com.zjt.takeoutproject.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

//文件上传和下载
@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {

    @Value("${takeoutproject.path}")
    private String basePath;

    //参数名要与上传的name保持一致
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        //file是一个临时文件，需要转存到指定位置
        log.info("文件信息：{}",file.toString());

        //获取原始文件名
        String originalFilename = file.getOriginalFilename();

        //获得动态后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用UUID重新生成文件名，防止文件名重复覆盖
        String filename = UUID.randomUUID().toString()+suffix;

        //创建储存目录
        File dir=new File(basePath);
        if(!dir.exists()){
            dir.mkdirs();
        }

        try {
            //将临时文件转存指定位置
            file.transferTo(new File(basePath+filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(filename);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse httpServletResponse){
        //通过输入流读取文件内容
        try {
            log.info("文件路径：{}",basePath+name);
            FileInputStream fileInputStream = new FileInputStream(new File(basePath+name));

            //通过输出流将文件写回浏览器，在浏览器显示图片
            ServletOutputStream outputStream=httpServletResponse.getOutputStream();

            httpServletResponse.setContentType("image/jpeg");
            int len=0;
            byte[] bytes = new byte[1024];
            while((len=fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
